Aug 25, 2023
HttpResponse object.set_cookie() method. For example:from django.http import HttpResponse
response = HttpResponse("Cookie Set!")
response.set_cookie('username', 'john_doe', max_age=3600) # Set the 'username' cookie with a lifespan of 1 hour (in seconds)set_cookie() method is used to add a cookie named ‘username’ with the value ‘john_doe’ and a maximum age of 3600 seconds (1 hour).request.COOKIES dictionary.def get_username(request):
username = request.COOKIES.get('username', 'Guest')
return f"Hello, {username}!"get() method is used to retrieve the value of the ‘username’ cookie from the request.COOKIES dictionary. If the cookie is not present, it defaults to ‘Guest’.response = HttpResponse("Cookie Deleted!")
response.set_cookie('username', '', expires='Thu, 01 Jan 1970 00:00:00 GMT')If you haven’t already, install Django:
Create a new Django project:
Now, let’s create a new app within the project:
In the cookiedemo directory, create a file named urls.py to define your URL patterns:
In the same student directory, modify the file named views.py to define your views:
from django.shortcuts import render
# Create your views here.
def setcookie(request):
response = render(request, 'student/setcookie.html')
response.set_cookie('name', 'ParleG', max_age=60)
return response
def getcookie(request):
#name = request.COOKIES['name']
name = request.COOKIES.get('name', "Guest") # no error and Guest return if key not present
return render(request, 'student/getcookie.html', {'name': name})
def delcookie(request):
response = render(request, 'student/delcookie.html')
response.delete_cookie('name')
return responsetemplates/student/setcookie.html
templates/student/getcookie.html
templates/student/delcookie.html
Now you can run the development server:
Visit these URLs in your browser to see the different views:
Check the developer tool of google chrome to check the cookie status
Manish Patel